<?php 
/***
    Amrita ITEWS - Copyright (C) 2009 Amrita Vishwa Vidyapeetham, Amritapuri.
                                     (http://www.amrita.edu)
    ***************************************************************************
    This file is part of the Amrita ITEWS distribution.
    Amrita ITEWS is free software; you can redistribute it and/or modify it 
    under the terms of the GNU General Public License (version 2) as published 
    by the Free Software Foundation AND MODIFIED BY the Amrita ITEWS exception.
    ***NOTE*** The exception to the GPL is included to allow you to distribute
    a combined work that includes Amrita ITEWS without being obliged to provide
    the source code for proprietary components outside of the Amrita ITEWS
    software. Amrita ITEWS is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
    Public License for more details. You should have received a copy of the GNU
    General Public License and the Amrita ITEWS license exception along with 
    Amrita ITEWS if not then it can be viewed here: 
    http://itews.amrita.ac.in/license.html.
    
    Documentation, latest information, license and contact details are at:
    http://itews.amrita.ac.in/
 
    Amrita ITEWS source code can be found at:
    http://code.google.com/p/itews"; 
    
    The initial code-base of Amrita ITEWS was developed by Amrita Vishwa 
    Vidyapeetham as part of the project titled,\"Intelligent & Interactive 
    Telematics using Emerging Wireless Technologies for Transport Systems 
    (ITEWS)\" sponsored by Technology Information Forecasting and Assessment 
    Council (TIFAC), India.
***/
?><?php
set_time_limit(0);//allow to run forever
date_default_timezone_set("Asia/Calcutta");

require_once("./settings.php.inc");
require_once("./utils.php.inc");
require_once("./download_worker.php");

trigger_error("Media Downloader started",E_USER_NOTICE);
trigger_error("Sleeping for some time so that Hotzone detector script can kick in",E_USER_NOTICE);
sleep(III_SLEEP_TIME);//GIVE TIME TO THE HOTZONE DETECTOR TO KICK IN

$sql = 'truncate curr_download_status;';

if ( ($result = query_wrapper($sql, __FILE__, __LINE__))==null){
	die ("Not able to inititalize database");
}

$sql = 'INSERT INTO curr_download_status (download_status ,logtime) VALUES (\'init\', NOW( ))';

if ( ($result = query_wrapper($sql, __FILE__, __LINE__))==null){
	die ("Not able to inititalize database");
}



$counter = 0;
$all_downloaded = false;

while (true){
try{	
	$hz_event_notification_error=false;
	
	///if (!check_hotzone_status() && $hz_event_notification_error){
	if (!check_hotzone_status()){
		//MAY HAVE IT LATER...BUT WILL GIVE BEEP OUTSIDE HOTZONE
		//if (!$all_downloaded)
			//echo "\x07";
		///if (!$hz_event_notification_error)
			trigger_error("Out of Hotzone area",E_USER_NOTICE);
		sleep(III_SLEEP_TIME);
		continue;
	}

	trigger_error("Inside Hotzone area",E_USER_NOTICE);

	trigger_error ("Starting download Iteration #".$counter++,E_USER_NOTICE);
	$sql = ' SELECT rs.route_schedule_code, rs.route_schedule_desc, rs.is_current_route, md.media_code, md.media_title, '
			. ' md.relative_media_path, tdmc.seq_no, md.percentage_downloaded, md.data_rate, md.is_not_found, md.last_known_status, md.absolute_media_path'
	        . ' FROM route_schedules rs, media_descriptors md, trigger_descriptors td, trigger_desc_media_components tdmc'
	        . ' WHERE '
	        . ' rs.route_schedule_code = td.route_schedule_code'
	        . ' AND td.id = tdmc.trigger_desc_id'
	        . ' AND tdmc.media_code = md.media_code'
			. ' AND md.relative_media_path != \'\''
			. ' AND md.percentage_downloaded < 100'
	        . ' AND rs.is_download_pending = \'T\''
	        . ' ORDER BY ASCII( rs.is_current_route ) DESC , rs.usage_count DESC , tdmc.seq_no';
	//LIMIT 1 is removed - because we also want to get a count of how many are there to be downloaded
	//SOME MODIFICATION CAN BE MADE HERE SO THAT THE MEDIA FOR THE NODE WHERE VEHICLE CURRENTLY IS, IS DOWNLOADED FIRST
	//THEN N+1 AND SO ON IN  CYCLIN WAY TILL N-1
	//THERE IS A CURR_NODE TABLE
	//AFTER POPULATING DOWNLOAD_INFO ARRAY, WE CAN SORT THE ARRAY IN A CYCLIC WAY

	while ( ($result = query_wrapper($sql, __FILE__, __LINE__, __FUNCTION__))==null){
		sleep(III_SLEEP_TIME);
		continue;
	}
	
	if (mysql_num_rows($result)==0)
	{
		trigger_error("Nothing to download",E_USER_NOTICE);
		$all_downloaded = true;
		sleep(1);
		for ($i=0;$i<3;$i++){
			if (BEEP_ENABLED)
				//echo NOTHING_TO_DOWNLOAD_BEEP;
				exec(NOTHING_TO_DOWNLOAD_BEEP);
			sleep(1);
		}
		sleep(III_SLEEP_TIME);
		continue;
	}

	$total_to_be_downloaded = count(mysql_num_rows($result));	
	$all_downloaded = false;

	$download_info_array = array();


	while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
		if (!array_key_exists($row['media_code'], $download_info_array)){
			$download_info_array[$row['media_code']]['media_title']= $row['media_title'];
			$download_info_array[$row['media_code']]['relative_media_path']= $row['relative_media_path'];
			$download_info_array[$row['media_code']]['percentage_downloaded'] = $row['percentage_downloaded'];
			$download_info_array[$row['media_code']]['data_rate'] = $row['data_rate'];
			$download_info_array[$row['media_code']]['is_not_found']= $row['is_not_found'];
			//$download_info_array[$row['media_code']]['absolute_media_path']= $row['absolute_media_path'];--update it always
			$download_info_array[$row['media_code']]['last_known_status']= $row['last_known_status'];
		}
	}

	$result = null;

	$last_known_percentage_downloaded = null;
	$last_known_data_rate = null;
	$previous_last_known_data_rate = null;
	$previous_last_known_percentage_downloaded = null;
	$is_not_found = null;
	$previous_is_not_found = null;
	$last_known_status = null;
	$previous_last_known_status = null;
	
	
	$data_has_changed = null;
	$changed_parameters_array = null;
	
	foreach($download_info_array as $info_key=>$info_value)
	//There we just iterate over the array so that we have to go thru unique set of media codes
	{
		$download_media_code = $info_key;
		$download_media_title = $info_value['media_title'];
		$download_media_relative_media_path = $info_value['relative_media_path'];
		//$download_route_schedule_code = $row['route_schedule_code'];
		//$download_route_schedule_desc = $row['route_schedule_desc'];
		//$download_is_for_current_route = $row['is_current_route'];
		$download_percentage_downloaded = $info_value['percentage_downloaded'];
		$download_data_rate = $info_value['data_rate'];
		$download_is_not_found = $info_value['is_not_found'];
		$download_last_known_status = $info_value['last_known_status'];
		$last_known_percentage_downloaded[$info_key] = $download_percentage_downloaded;
		$previous_last_known_percentage_downloaded[$info_key] = $download_percentage_downloaded;
		$last_known_data_rate[$info_key] = $download_data_rate;
		$previous_last_known_data_rate[$info_key] = $download_data_rate;
		$is_not_found[$info_key] = $download_is_not_found;
		$previous_is_not_found[$info_key] = $download_is_not_found;
		$last_known_status[$info_key] = $download_last_known_status;
		$previous_last_known_status[$info_key]= $download_last_known_status;
		
		$data_has_changed[$info_key]=false;
		$changed_parameters_array = array();

		$current_media_url = str_replace("\\","/",$download_media_relative_media_path);
			
		//take the folder info from it and make sure that the folder is created	
		while (substr($current_media_url, -1)=="/")
		{
			$current_media_url = substr($current_media_url,0,-1);//remove all slashes from end
		}
			
		//while (substr($current_media_url, 0,1)=="/")
		while ($current_media_url{0}=="/")
		{
			$current_media_url = substr($current_media_url,1);//remove all slashes from beginning			
		}
			
		$current_media_file_name = substr($current_media_url,strrpos($current_media_url,'/')+1);
			
		$folder_structure = substr($current_media_url,0,strrpos($current_media_url,'/'));

		if ($folder_structure != '')
			$folder_structure = MEDIA_FILE_ROOT_FOLDER."/".$folder_structure;
		else
			$folder_structure = MEDIA_FILE_ROOT_FOLDER;
				
		create_folder_structure($folder_structure);

		download_media();
		
		//if media is not downloaded...give single beep
		if ($is_not_found[$info_key]){
			if (BEEP_ENABLED)
				//echo NOT_FOUND_BEEP;
				exec(NOT_FOUND_BEEP);
			sleep(I_SLEEP_TIME);
		}

		if (!check_hotzone_status()){
			trigger_error("Out of Hotzone area",E_USER_NOTICE);
			sleep(III_SLEEP_TIME);
			break;
		}
	}

	sleep(III_SLEEP_TIME);
}
catch (Exception $e){
	trigger_error("EXCEPTION: ".$e->getMessage(),E_USER_WARNING);
	sleep(III_SLEEP_TIME);
	continue;
}
}

function check_hotzone_status(){
	global $media_cache_ip_port;
	global $link;
	
	global $hz_event_notification_error;
	$hz_event_notification_error = false;

	$hz_sql = 'SELECT is_in_media_hotzone, node_code, media_cache_ip_port from curr_media_hotzone_status where is_in_media_hotzone = \'T\' and '
			. ' ABS(TIMESTAMPDIFF(SECOND,logtime,NOW()))<='.HOTZONE_EVENT_TIMEOUT.' LIMIT 1;';
	
	while ( ($hz_rs = query_wrapper($hz_sql, __FILE__, __LINE__, __FUNCTION__))==null){
		sleep(III_SLEEP_TIME);
		continue;
	}


	if(mysql_num_rows($hz_rs)>0){
		while ($hz_row = mysql_fetch_array($hz_rs, MYSQL_ASSOC)){
			$media_cache_ip_port = $hz_row['media_cache_ip_port'];
			break;//only once
		} 
		trigger_error("Database entry found for current hotzone's media cache IP-Address/Port:".$media_cache_ip_port,E_USER_NOTICE);
		return true;
	}
	else{
		//$hz_event_notification_error = true;
		//trigger_error("No database entry or stale entry for current hotzone",E_USER_NOTICE);
		return false;
	}
}

function create_folder_structure( $fs ){
    $folder = explode( "/" , $fs );

    if ($fs{0}=="/")
		$mkfolder = '/';
	else
		$mkfolder = '';
    
	for(  $i=0 ; isset( $folder[$i] ) ; $i++ ){
		if (trim($folder[$i])=="")
			continue;
        $mkfolder .= $folder[$i];
		if (trim($mkfolder)=="")
			continue;
        if( !is_dir( $mkfolder ) )
		{
			mkdir( "$mkfolder" ,  0777);
			trigger_error("Creating folder ".$mkfolder, E_USER_NOTICE);
		}
        $mkfolder .= '/';
        }
}

?>
